package com.star.file.controller;

import com.star.entity.Result;
import com.star.entity.StatusCode;
import com.star.file.util.FastDFSClient;
import com.star.file.util.FastDFSFile;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/*
			  ________   ___   ___        ___   ________   ___   ___        ___
	 ________|\   __  \_|\  \_|\  \______|\  \_|\   __  \_|\  \_|\  \______|\  \_________
	 \       \ \  \_\ /_\ \  \\ \  \     \ \  \\ \  \_\ /_\ \  \\ \  \     \ \  \        \
	  \       \ \   __  \\ \  \\ \  \     \ \  \\ \   __  \\ \  \\ \  \     \ \  \        \
	   \       \ \  \_\  \\ \  \\ \  \____ \ \  \\ \  \_\  \\ \  \\ \  \____ \ \  \        \
	    \       \ \_______\\ \__\\ \_______\\ \__\\ \_______\\ \__\\ \_______\\ \__\        \
	     \       \|_______| \|__| \|_______| \|__| \|_______| \|__| \|_______| \|__|         \
	 	  \___________________________________________________________________________________\

*/
@RestController
@RequestMapping("/file")
public class FileController {
    @PostMapping("/upload")
    public Result uploadFile(MultipartFile file) {
        try {
            //1.判断文件是否存在
            if (file == null) {
                throw new RuntimeException("文件不存在");
            }
            //2.获取文件的完整名称
            String filename = file.getOriginalFilename();
            if (StringUtils.isEmpty(filename)) {
                throw new RuntimeException("文件不存在");
            }
            //3.获取文件扩展名称
            String extName = filename.substring(filename.lastIndexOf(".") + 1);
            //4.获取文件内容
            byte[] fileBytes = file.getBytes();
            //5.创建文件上传封装实体类
            FastDFSFile fastDFSFile = new FastDFSFile(filename, fileBytes, extName);
            //6.基于工具类完成文件上传，接收返回的参数
            String[] upload = FastDFSClient.upload(fastDFSFile);
            String url = FastDFSClient.getTrackerUrl() + upload[0] + "/" + upload[1];
            //7.封装返回结果

            return new Result(true, StatusCode.OK, "文件上传成功", url);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, StatusCode.ERROR, "文件上传失败");
    }
}
